package com.wang.config;

import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;

public class DubboServiceBuilder<T> {

    private DubboServiceBuilder(){

    }

    public DubboServiceBuilder(Class<T> type, String group,String version,int timeout,String registryAddress){
        this.type = type;
        this.group = group;
        this.version = version;
        this.timeout = timeout;
        this.registryAddress = registryAddress;
    }
    private T service;

    private Class<T> type;

    private String group;

    private String version;

    private int timeout;

    private String registryAddress;

    public T getService() {
        if(service != null){
            return  service;
        }
        buildService();
        return service;
    }

    private void buildService(){
        //创建服务应用对象实例
        ReferenceConfig<T> referenceConfig = new ReferenceConfig<>();
        //设置应用程序信息
        referenceConfig.setApplication(new ApplicationConfig("dubbo-consumer"));
        //设置服务注册中心
        referenceConfig.setRegistry(new RegistryConfig(registryAddress));
        //设置服务接口和超时时间
        referenceConfig.setInterface(type);
        referenceConfig.setTimeout(timeout);
        //设置负载策略和集群容错策略
        //referenceConfig.setLoadbalance("myLoadBalance");
        //referenceConfig.setCluster("myBroadcast");
        //设置服务的版本号和分组
        referenceConfig.setVersion(version);
        referenceConfig.setGroup(group);
        referenceConfig.setCheck(false);
        service = referenceConfig.get();
    }
}
